package com.wetool.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.wetool.entity.PublicCommodity;
import com.wetool.model.SearchParam;

public class PublicCommoditySpec implements Specification<PublicCommodity> {

	private final SearchParam params;
	private final Long[] categoryIds;

	public PublicCommoditySpec( SearchParam params, Long[] categoryIds) {
		this.params = params;
		this.categoryIds = categoryIds;
	}

	@Override
	public Predicate toPredicate(Root<PublicCommodity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

		List<Predicate> predicates = new ArrayList<>();
		// 判断商品条码或名称
		if (StringUtils.isNotBlank(params.getKey())) {
			Predicate pred = cb.or(cb.like(cb.lower(root.get("name")), "%" + params.getKey() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("barcode")), "%" + params.getKey() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("pinyin")), "%" + params.getKey() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("pinyinShorthand")), "%" + params.getKey() + "%"));
			predicates.add(pred);
		}
		// 商品分类
		if (params.getCategoryId() != null) {
			Predicate pred = null;
			for (int l = 0; l < categoryIds.length; l++) {
				if (l == 0) {
					pred = cb.or(cb.equal(root.get("categoryId"), categoryIds[l]));// 拼接sql
																					// null不能开头
				}
				pred = cb.or(pred, cb.equal(root.get("categoryId"), categoryIds[l]));
			}
			predicates.add(pred);
		}
		// 创建时间比对
//		// 日期格式大于
//		if (params.getFrom() != null) {
//			predicates.add(cb.greaterThan(root.get("createTime"), params.getFrom()));
//		}
//		if (params.getTo() != null) {
//			predicates.add(cb.lessThan(root.get("createTime"), params.getTo()));
//		}
		return andTogether(predicates, cb);
	}

	private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
		return cb.and(predicates.toArray(new Predicate[0]));
	}
}